package cn.virens.web.components.open.wxmp.config;

import cn.virens.web.components.open.wxmp.config.cache.WxMpConfigCache;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.enums.TicketType;

/**
 * 微信配置信息公共类
 * 
 * @author virens
 */
public class WxMpCacheConfigSimple extends WxMpDefaultConfigImpl {
	private static final long serialVersionUID = 4942623449321990595L;
	private static final String ACCESS_TOKEN = "access_token";

	private WxMpConfigCache mWxMpConfigCache;

	@Override
	public String getAccessToken() {
		return mWxMpConfigCache.get(key(ACCESS_TOKEN));
	}

	@Override
	public boolean isAccessTokenExpired() {
		return mWxMpConfigCache.ttl(key(ACCESS_TOKEN)) < 2;
	}

	@Override
	public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
		mWxMpConfigCache.set(key(ACCESS_TOKEN), accessToken, expiresInSeconds - 200);
	}

	@Override
	public void expireAccessToken() {
		mWxMpConfigCache.rm(key(ACCESS_TOKEN));
	}

	@Override
	public String getTicket(TicketType type) {
		return mWxMpConfigCache.get(key(type));
	}

	@Override
	public boolean isTicketExpired(TicketType type) {
		return mWxMpConfigCache.ttl(key(type)) < 2;
	}

	@Override
	public synchronized void updateTicket(TicketType type, String jsapiTicket, int expiresInSeconds) {
		mWxMpConfigCache.set(key(type), jsapiTicket, expiresInSeconds - 200);
	}

	@Override
	public void expireTicket(TicketType type) {
		mWxMpConfigCache.rm(key(type));
	}

	public WxMpConfigCache getWxMpConfigCache() {
		return mWxMpConfigCache;
	}

	public void setWxMpConfigCache(WxMpConfigCache mWxMpConfigCache) {
		this.mWxMpConfigCache = mWxMpConfigCache;
	}

	private String key(String key) {
		return String.format("weixin:mp:config:%s:%s", getAppId(), key);
	}

	private String key(TicketType type) {
		return key(type.name());
	}

}
